#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: liang kang
@contact: gangkanli1219@gmail.com
@time: 2018/5/24 10:49
@desc: 
"""
from pathlib import Path

import numpy as np
import pydicom as dicom


def merge_dict(*dicts):
    res = {}
    for _dict in dicts:
        for key, value in _dict.items():
            if key not in res:
                res[key] = value
            else:
                res[key] += value
    return res


def merge_nodule(nodule_list):

    def _merge_nodule(nodules):
        if 1 == len(nodules):
            return nodules[0]
        nodule = nodules[0]
        for n in nodules[1:]:
            nodule.merge_nodule(n)
        return nodule

    nodule_pool = merge_dict(*[{str(nodule.index_id): [nodule]}
                               for nodule in nodule_list])
    return [_merge_nodule(value) for _, value in nodule_pool.items()]


def check_spacing(spacing_img, spacing_io):
    spacing = [0, 0, 0]
    if 0.4 < float(spacing_img[0]) < 1.0 and 0.4 < float(spacing_img[1]) < 1.0:
        spacing[0] = float(spacing_img[0])
        spacing[1] = float(spacing_img[1])
    elif 0.4 < float(spacing_io[0]) < 1.0 and 0.4 < float(spacing_io[1]) < 1.0:
        spacing[0] = float(spacing_io[0])
        spacing[1] = float(spacing_io[1])
    else:
        return None

    if 0.5 < float(spacing_img[2]) < 10:
        spacing[2] = float(spacing_img[2])
    elif 0.5 < float(spacing_io[2]) < 10:
        spacing[2] = float(spacing_io[2])
    else:
        return None

    return spacing


def get_frame_instance(dcm_dir, first_instance):
    frame_instance = {}
    min_instance, max_instance = 1000, 0
    for file in Path(dcm_dir).glob('*.dcm'):
        dcm = dicom.dcmread(str(file))
        frame_instance[dcm.SOPInstanceUID] = int(dcm.InstanceNumber)
        min_instance = min(min_instance, int(dcm.InstanceNumber))
        max_instance = max(max_instance, int(dcm.InstanceNumber))
    if first_instance == min_instance:
        return {key: value - min_instance for key, value in
                frame_instance.items()}
    elif first_instance == max_instance:
        return {key: max_instance - value for key, value in
                frame_instance.items()}
    else:
        return None


def average_distance2point(mask, point):
    point = np.asarray(point).reshape([1, 3])
    points = np.asarray(np.nonzero(mask)).T
    points = np.subtract(points, point)
    points *= points
    points = np.sum(points, axis=1)
    return np.mean(points)
